/**
 *
 */
package com.angel.email.attachments.strategies.impl.multiple;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.activation.DataHandler;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;

import com.angel.common.keyValue.KeyValueResult;
import com.angel.email.attachments.EmailAttachmentInfo;
import com.angel.email.attachments.manager.EmailAttachmentManager;
import com.angel.email.attachments.strategies.AttachmentsStrategy;
import com.angel.email.exceptions.EmailAccessException;
import com.angel.email.exceptions.EmailAttachmentException;
import com.angel.webapp.file.FileInformation;



/**
 * @author William.
 * @since 14/August/2009
 *
 */
public class MultiPartsAttachmentsStrategy implements AttachmentsStrategy{

	public FileInformation getAttachmentsFrom(Part part, KeyValueResult simpleAttachmentsStrategies) throws EmailAttachmentException {
		FileInformation fi;
		try {
			fi = new EmailAttachmentInfo(
					part.getContentType(),
					part.getFileName(),
					part.getInputStream(),
					part.getSize()
			);
		} catch (MessagingException e) {
			//TODO Write comments.
			throw new EmailAttachmentException("", e);
		} catch (IOException e) {
			//TODO Write comments.
			throw new EmailAttachmentException("", e);
		}
		return fi;
	}

	public List<FileInformation> getAttachmentsFrom(DataHandler dataHandler, KeyValueResult attachmentsStrategies) throws EmailAttachmentException {
		List<FileInformation> filesInformation = new ArrayList<FileInformation>();
		Multipart multipart;
		try {
			AttachmentsStrategy attachmentStrategy = EmailAttachmentManager.getAttachmentStrategy(attachmentsStrategies, dataHandler.getContentType());
			multipart = (Multipart) dataHandler.getContent();
			Integer countParts = multipart.getCount();
			for(int i = 0; i < countParts; i++){
				Part part = multipart.getBodyPart(i);
				FileInformation fileInformation = attachmentStrategy.getAttachmentFrom(part.getDataHandler());
				filesInformation.add(fileInformation);
			}
		} catch (IOException e) {
			throw new EmailAttachmentException("", e);
		} catch (MessagingException e) {
			throw new EmailAttachmentException("", e);
		}
		return filesInformation;
	}

	public FileInformation getAttachmentFrom(DataHandler dataHandler) throws EmailAccessException {
		FileInformation fi;
		try {
			fi = new EmailAttachmentInfo(
					dataHandler.getContentType(),
					dataHandler.getName(),
					dataHandler.getInputStream(),
					0
					);
		} catch (IOException e) {
			//TODO Write comments.
			throw new EmailAttachmentException("", e);
		}
		return fi;
	}
}
